import requests
import json

def get_top_songs_by_country(authorization):
    headers = {
        'accept': 'application/json',
        'accept-language': 'zh-CN,zh;q=0.9',
        'app-platform': 'Browser',
        'authorization': authorization,
        'cache-control': 'no-cache',
        'content-type': 'application/json',
        'origin': 'https://charts.spotify.com',
        'pragma': 'no-cache',
        'priority': 'u=1, i',
        'referer': 'https://charts.spotify.com/',
        'sec-ch-ua': '"Google Chrome";v="131", "Chromium";v="131", "Not_A Brand";v="24"',
        'sec-ch-ua-mobile': '?0',
        'sec-ch-ua-platform': '"Windows"',
        'sec-fetch-dest': 'empty',
        'sec-fetch-mode': 'cors',
        'sec-fetch-site': 'same-site',
        'spotify-app-version': '0.0.0.production',
        'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/131.0.0.0 Safari/537.36',
    }

    # 示例 API URL 模板
    country_urls = {
        "India":"https://charts-spotify-com-service.spotify.com/auth/v0/charts/regional-in-weekly/2024-11-14",
        "Australia": 'https://charts-spotify-com-service.spotify.com/auth/v0/charts/regional-us-weekly/latest',
        "Indonesia": 'https://charts-spotify-com-service.spotify.com/auth/v0/charts/regional-id-weekly/latest',
    }

    # 存储所有国家的歌曲数据
    songs_data = {"country": {}}  # 最外层增加 "country"

    for country, url in country_urls.items():
        response = requests.get(url, headers=headers)

        if response.status_code == 200:
            try:
                data_list = response.json()
                entries = data_list.get('entries', [])
                country_songs = []

                for data in entries[:10]:  # 获取前10首歌曲
                    track_name = data.get('trackMetadata', {}).get('trackName', 'Unknown Track')
                    artists_list = data.get('trackMetadata', {}).get('artists', [])
                    artist_names = ", ".join(artist.get('name', 'Unknown Artist') for artist in artists_list)

                    country_songs.append({
                        "track_name": track_name,
                        "artist_names": artist_names
                    })

                # 将国家的数据添加到结果字典
                songs_data["country"][country] = country_songs


            except Exception as e:
                print(f"Error parsing response for {country}: {e}")
        else:
            print(f"Request failed for {country} with status code {response.status_code}: {response.text}")

    # 将数据写入 JSON 文件
    with open('songs_data.json', 'w', encoding='utf-8') as json_file:
        json.dump(songs_data, json_file, ensure_ascii=False, indent=4)

    print("Data written to songs_data.json successfully!")
